
import Vue from "vue";
import Vuex, {Store} from 'vuex'
import { Message } from "element-ui";
import {getUserInfo,userLogOut} from "../api/login";
import router from '../router/index'

Vue.use(Vuex)

const store = new Store({
    state:{
        userInfo:JSON.parse(window.localStorage.getItem('userInfo')),
        token:window.localStorage.getItem('token')
    },
    mutations:{
        setUserInfo(state,playLoad){
            state.userInfo = playLoad
        },
        adminOut(state){
            state.userInfo = ''
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('userInfo')
            window.localStorage.removeItem('currentPath')
        }
    },
    actions:{
        async getUserInfo(content){
            const res = await getUserInfo()
            if(res && res.status === 200){
                content.commit('setUserInfo',res.data)
                window.localStorage.setItem('userInfo',JSON.stringify(res.data))
            }else {
                return
            }

            // console.log(res);
        },

        // 退出登录
        async logOut(content){
            const res = await userLogOut()
            if(res && res.status === 204){
                Message.success('退出成功')
                router.push({path:'/login'})
                content.commit('adminOut')
            }else{
                Message.error('网络错误')
            }
        }
    }
})

export default  store